package com.infinitus.activity.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.infinitus.activity.config.ActivityConfig;
import com.infinitus.activity.pojo.DO.AuldrawAddressDo;
import com.infinitus.activity.pojo.DO.AuldrawVo;
import com.infinitus.activity.pojo.DO.AuldrawWinnerDo;
import com.infinitus.activity.pojo.VO.QualificationVo;
import com.infinitus.activity.pojo.VO.ResponseVO;
import com.infinitus.activity.service.AuldrawService;
import com.infinitus.activity.util.KeyGenerator;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.security.Key;
import java.util.*;

/**
 * @author: luzhenjie
 * @create: 2019/3/11
 * @desc:
 */
@Controller
@RequestMapping(value = "/auldraw")
public class AuldrawController {

    private static Logger logger = Logger.getLogger(AuldrawController.class);

    @Autowired
    private AuldrawService auldrawService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private String redisPort;

    @Value("${deploycolId}")
    private String deploycolId;

    @Autowired
    private ActivityConfig activityConfig;

    /**
     * @Desc 根据卡号获取中奖纪录
     */
    @RequestMapping(value = "/winner/record", method = RequestMethod.GET)
    public ResponseEntity<?> selectAuldrawWinnerListByCardNo(String dealerNo) {
            Jedis jedis = null;
            Map<String , AuldrawVo> map = new HashMap<>();
            try {
                jedis = new Jedis(redisHost,Integer.valueOf(redisPort));
                jedis.connect();
                Map<String, String> stringMap = jedis.hgetAll(KeyGenerator.getActivityListWinningBackup(deploycolId,dealerNo));
                for (Map.Entry<String, String> entry : stringMap.entrySet()) {
                    AuldrawVo auldrawVo = JSONObject.parseObject(entry.getValue(), AuldrawVo.class);
                    map.put(entry.getKey(), auldrawVo);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(jedis != null) {
                    jedis.close();
                }
            }
            return ResponseEntity.ok(new ResponseVO<>().setContent(map));
    }

    /**
     * @Desc 填写收货地址
     */
   /* @RequestMapping(value = "/address/create" ,method = RequestMethod.POST)
    public ResponseEntity<?> createAuldrawAddress(@RequestBody AuldrawAddressDo auldrawAddressDo) {
        try {
            auldrawAddressDo.setCreateTime(new Date());
            auldrawService.createAuldrawAddress(auldrawAddressDo);
            return ResponseEntity.ok(new ResponseVO<>().setContent("保存地址成功"));
        }catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(new ResponseVO<>().setContent("保存地址失败"));
        }
    }*/

    @RequestMapping(value = "/address/create",method = RequestMethod.POST)
    public ResponseEntity<?> createAuldrawAddress(@RequestBody AuldrawVo auldrawVo) {
            Jedis jedis = null;
            try {
                //将收货地址保存到redis中
                String dealerNo = auldrawVo.getDealerNo();       //卡号
                String qualiSeqNo = auldrawVo.getQualiSeqNo();   //资格序列号
                //获取卡号对应的中奖纪录
                jedis = new Jedis(redisHost,Integer.valueOf(redisPort));
                jedis.connect();
                String jsonString = jedis.hget(KeyGenerator.getActivityListWinningBackup(deploycolId,dealerNo), qualiSeqNo);
                AuldrawVo auldrawVo1 = JSONObject.parseObject(jsonString, AuldrawVo.class);
                //保存收货信息
                auldrawVo1.setPorcCode(auldrawVo.getPorcCode());
                auldrawVo1.setReceiverName(auldrawVo.getReceiverName());
                auldrawVo1.setReceiverPhone(auldrawVo.getReceiverPhone());
                auldrawVo1.setProvinceCode(auldrawVo.getProvinceCode());
                auldrawVo1.setCityCode(auldrawVo.getCityCode());
                auldrawVo1.setTownCode(auldrawVo.getTownCode());
                auldrawVo1.setDetailAddress(auldrawVo.getDetailAddress());
                //设置回Redis
                jedis.hset(KeyGenerator.getActivityListWinningBackup(deploycolId,dealerNo),qualiSeqNo,JSON.toJSONString(auldrawVo1));
                return ResponseEntity.ok(new ResponseVO<>().setContent("保存地址成功"));
            }catch (Exception e) {
                e.printStackTrace();
                return ResponseEntity.ok(new ResponseVO<>().setContent("保存地址失败"));
            }finally {
                if(jedis != null) {
                    jedis.close();
                }
            }
    }


    /**
     * @Desc 根据卡号获取资格可抽奖次数
     */
    @RequestMapping(value = "/quali/count" ,method = RequestMethod.GET)
    public ResponseEntity<?> qualiCount(String dealerNo) {
        Map<String , AuldrawVo> map = new HashMap<>();
        Jedis jedis = null;
        int count = 0;
        try {
            jedis = new Jedis(redisHost,Integer.valueOf(redisPort));
            jedis.connect();
            Map<String, String> stringMap = jedis.hgetAll(dealerNo);
            for (Map.Entry<String, String> entry : stringMap.entrySet()) {
                QualificationVo qualificationVo = JSONObject.parseObject(entry.getValue(), QualificationVo.class);
                if(qualificationVo.getQualiStatus() == 1) {
                    count++;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(jedis != null) {
                jedis.close();
            }
        }
        return ResponseEntity.ok(new ResponseVO<>().setContent(count));

    }


    /**
     * 根据卡号获取已填写的收货地址
     *
     * @param cardNo
     * @return
     */
    @RequestMapping(value = "/address/{cardNo}", method = RequestMethod.GET)
    public ResponseEntity<?> selectAuldrawAddressListByCardNo(@PathVariable("cardNo") String cardNo) {
        List<AuldrawAddressDo> auldrawAddressDoList = auldrawService.selectAuldrawAddressListByCardNo(cardNo);
        return ResponseEntity.ok(new ResponseVO<>().setContent(auldrawAddressDoList));
    }
}